
package com.zkmonitor.interceptor;

import java.util.List;

import com.zkmonitor.common.UserHolder;
import com.zkmonitor.exception.ShepherException;
import com.zkmonitor.model.User;
import com.zkmonitor.util.ZkMonitorConstants;

import org.apache.commons.lang3.StringUtils;
import org.jasig.cas.client.util.AbstractCasFilter;
import org.jasig.cas.client.validation.Assertion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.ldap.userdetails.LdapUserDetailsImpl;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class PassportInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(PassportInterceptor.class);

   
    @Autowired
    private UserHolder userHolder;

    @Value("${server.login.type}")
    private String loginType;

    @Value("${demo.admin.name}")
    private String demoAdminName;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        return holdUser(request);
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
        userHolder.clean();
    }

    private boolean holdUser(HttpServletRequest request)
            throws ShepherException {
        String userName = null;
        String role=null;
        if (ZkMonitorConstants.LOGIN_TYPE_LDAP.equals(loginType.toUpperCase())) {
            SecurityContextImpl context =
                    (SecurityContextImpl) request.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
            if (context != null) {
                userName = ((LdapUserDetailsImpl) context.getAuthentication().getPrincipal()).getUsername();
            }
        } else if (ZkMonitorConstants.LOGIN_TYPE_CAS.equals(loginType.toUpperCase())) {
            Assertion assertion = (Assertion) request.getSession().getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
            userName = assertion.getPrincipal().getName();
        } else if (ZkMonitorConstants.LOGIN_TYPE_DEMO.equals(loginType.toUpperCase())) {
            SecurityContextImpl context =
                    (SecurityContextImpl) request.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
            if (context != null) {
            	
                userName = ((UserDetails) context.getAuthentication().getPrincipal()).getUsername();
                List<GrantedAuthority>  uu=(List<GrantedAuthority> ) context.getAuthentication().getAuthorities();
                role=uu.get(0).getAuthority();
            }
        } else {
            throw ShepherException.createIllegalLoginTypeException();
        }
      
      
        if (!StringUtils.isEmpty(userName)){
        	 User user = new User();
        	 user.setName(userName);
        	 if (role!=null){
        		 user.setRole(role);
        	 }
             userHolder.setUser(user);
        }
        return true;
    }

}
